# frozen_string_literal: true

class UsersController < ApplicationController
  wechat_api
  def index
    @current_user = User.find(session['user_id'])
    @address = @current_user.address || @current_user.build_address
  end

  def update
    @current_user = User.find(session['user_id'])
    if params[:address_id].blank?
      address = Address.new(params.permit(:province, :city, :district, :street))
      address.user_id = @current_user.id
      if address.save
        if @current_user.update(user_params)
          render 'update'
          # redirect_to @current_user
        else
          render 'message'
          # redirect_to request.referer, notice: '请完善会员信息！'
        end
      else
        render 'message'
        # redirect_to request.referer, notice: '请完善会员信息！'
      end
    else
      address = Address.find(params[:address_id])
      if address.update(params.permit(:province, :city, :district, :street))
        if @current_user.update(user_params)
          # redirect_to @current_user
          render 'update'
        else
          render 'message'
          # redirect_to request.referer, notice: '请完善会员信息！'
        end
      else
        render 'message'
        # redirect_to request.referer, notice: '请完善会员信息！'
      end
    end
 end

  def show
    @current_user = User.find(session['user_id'])
  end

  private

  def user_params
    params.permit(:name, :phone, :address, :pet_birth, pets: [])
  end
end
